package com.yusp75.myexam.com.yusp75.myexam.ui.books

import android.annotation.SuppressLint
import android.app.AlertDialog
import android.graphics.Color
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.yusp75.myexam.data.Book
import com.yusp75.myexam.databinding.ItemBookBinding

import java.util.Locale
import androidx.core.graphics.toColorInt
import com.yusp75.myexam.data.BookWithCounts
import java.time.LocalDate
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import kotlin.time.ExperimentalTime
import java.time.Instant

class BookAdapter(
    private val onSelectClick: (Book) -> Unit,
    private val onDeleteClick: (Book) -> Unit
) : ListAdapter<BookWithCounts, BookAdapter.ViewHolder>(DiffCallback) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val binding = ItemBookBinding.inflate(
            LayoutInflater.from(parent.context), parent, false
        )
        return ViewHolder(binding)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bind(getItem(position))
    }

    inner class ViewHolder(private val binding: ItemBookBinding) :
        RecyclerView.ViewHolder(binding.root) {
        val formatter: DateTimeFormatter =
            DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.getDefault())

        @SuppressLint("SetTextI18n")
        @OptIn(ExperimentalTime::class)
        fun bind(book: BookWithCounts) {
            binding.apply {
                bookName.text = book.book.name
                countOfQuestionInBook.text =
                    "题数量：${book.totalQuestions}，判断：${book.singleChoiceCount} ， 选择：${book.judgeCount}"
                /*                bookUpdated.text = "创建时间：" +
                                    SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(Date(book.createdAt))*/
                val createdAtDate: LocalDate =
                    Instant.ofEpochMilli(book.book.createdAt).atZone(ZoneId.systemDefault())
                        .toLocalDate()
                bookUpdated.text = "创建时间：${createdAtDate.format(formatter)}"

                // 背景色
                root.setBackgroundColor(
                    if (book.book.isSelected) "#E3F2FD".toColorInt()
                    else Color.TRANSPARENT
                )
                // 删书
                btnDeleteBook.setOnClickListener {
                    AlertDialog.Builder(binding.root.context)
                        .setTitle("删除确认")
                        .setMessage("确定要删除《${book.book.name}》吗？")
                        .setPositiveButton("删除") { _, _ ->
                            onDeleteClick(book.book) // 用户确认后执行删除
                        }
                        .setNegativeButton("取消", null)
                        .show()
                }
                // 选择书
                btnSelectBook.setOnClickListener {
                    onSelectClick(book.book)
                }

            }

            // fun bind
        }
    }

    companion object {
        private val DiffCallback = object : DiffUtil.ItemCallback<BookWithCounts>() {
            override fun areItemsTheSame(oldItem: BookWithCounts, newItem: BookWithCounts) =
                oldItem.book.id == newItem.book.id

            override fun areContentsTheSame(oldItem: BookWithCounts, newItem: BookWithCounts) =
                oldItem == newItem
        }
    }
}
